package algorithm;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Administrator on 2017/7/7.
 * 处理带有#include的文件，并且输出这些文件
 */
public class ProcessInclude {

    /**
     * 处理文件，打印当前文件内容
     * 当读取到`#include`的时候，则读取后面引用的文件
     * @param fileName
     * @throws IOException
     */
    public static void processFile(String fileName) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        StringBuilder sb = new StringBuilder();
        Set<String> fileNames = new HashSet<>();
        String line="";
        while ((line=reader.readLine())!=null&&line!=""){
            sb.append(line);
            sb.append("\n");
            String name = "";
            if ((name = searchFileName(line))!=null&&!"".equals(name)){
                if (!name.equals(fileName))
                    fileNames.add(name);
            }
            line="";
        }
        System.out.println(sb);
        //扫描到引用的其他文件，就读取，处理并且打印
        if (fileNames.size()>0){
            for (String finame:fileNames){
                processFile(finame);
            }
        }
    }

    /**
     * 挑出Include的文件名，默认一行只有一条include
     * @param line
     * @return
     */
    private static String searchFileName(String line){
        String[] words = line.split(" ");
        for (int i = 0; i <words.length ; i++) {
            if (words[i].equals("#include")&&i<words.length-1){
               return words[i+1];
            }
        }
        return null;
    }

}
